<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreAfterSalesRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'order_id' => 'required|exists:orders,id',
            'type' => 'required|in:return,refund,exchange',
            'reason' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'images' => 'nullable|array|max:5',
            'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
            'items' => 'required|array|min:1',
            'items.*.order_item_id' => 'required|exists:order_items,id',
            'items.*.quantity' => 'required|integer|min:1',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'order_id.required' => '请选择订单',
            'order_id.exists' => '订单不存在',
            'type.required' => '请选择售后类型',
            'type.in' => '售后类型无效',
            'reason.required' => '请填写售后原因',
            'reason.max' => '售后原因不能超过255个字符',
            'description.max' => '详细描述不能超过1000个字符',
            'images.array' => '图片格式错误',
            'images.max' => '最多只能上传5张图片',
            'images.*.image' => '文件必须是图片',
            'images.*.mimes' => '图片格式必须是jpeg、png、jpg或gif',
            'images.*.max' => '图片大小不能超过2MB',
            'items.required' => '请选择要申请售后的商品',
            'items.min' => '至少选择一个商品',
            'items.*.order_item_id.required' => '请选择商品',
            'items.*.order_item_id.exists' => '商品不存在',
            'items.*.quantity.required' => '请输入数量',
            'items.*.quantity.integer' => '数量必须是整数',
            'items.*.quantity.min' => '数量不能少于1',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // 验证订单是否属于当前用户
            if ($this->order_id) {
                $order = \App\Models\Order::find($this->order_id);
                if ($order && $order->user_id !== auth()->id()) {
                    $validator->errors()->add('order_id', '无权操作此订单');
                }
            }

            // 验证订单项是否属于指定订单
            if ($this->items) {
                $orderItemIds = collect($this->items)->pluck('order_item_id');
                $orderItems = \App\Models\OrderItem::whereIn('id', $orderItemIds)->get();
                
                foreach ($orderItems as $item) {
                    if ($item->order_id != $this->order_id) {
                        $validator->errors()->add('items', '所选商品不属于指定订单');
                        break;
                    }
                }
            }
        });
    }
}